# frozen_string_literal: true

require 'spec_helper'

RSpec.describe GitlabSchema.types['VulnerabilityScanner'] do
  let_it_be(:group) { create(:group) }
  let_it_be(:project) { create(:project, namespace: group) }
  let_it_be(:user) { create(:user) }

  let(:fields) do
    %i[id name external_id vendor report_type report_type_humanized]
  end

  before do
    stub_licensed_features(security_dashboard: true)

    project.add_developer(user)
  end

  subject { GitlabSchema.execute(query, context: { current_user: user }).as_json }

  it { expect(described_class).to have_graphql_fields(fields) }
  it { expect(described_class).to require_graphql_authorizations(:read_vulnerability_scanner) }

  context 'when responding with a non-persisted object' do
    let_it_be(:pipeline) { create(:ee_ci_pipeline, :with_sast_report, project: project) }

    let(:query) do
      %(
        query {
          project(fullPath: "#{project.full_path}") {
            pipeline(iid: "#{pipeline.iid}") {
              securityReportFindings {
                nodes {
                  title
                  scanner {
                    id
                    name
                    reportType
                    reportTypeHumanized
                    externalId
                  }
                }
              }
            }
          }
        }
      )
    end

    before do
      stub_licensed_features(sast: true, security_dashboard: true)
    end

    describe 'id' do
      context 'when the scanner id is nil' do
        it 'sets the id to null' do
          security_findings = subject.dig('data', 'project', 'pipeline', 'securityReportFindings', 'nodes')

          expect(security_findings.map { |finding| finding['scanner']['id'] }.uniq.first).to be_nil
          expect(security_findings.map { |finding| finding['scanner']['reportType'] }.uniq.first).to eq('SAST')
        end
      end

      context 'when the scanner id is present' do
        let_it_be(:scanner_sast) { create(:vulnerabilities_scanner, project: project, external_id: 'find_sec_bugs') }

        it 'calculates the global ID' do
          security_findings = subject.dig('data', 'project', 'pipeline', 'securityReportFindings', 'nodes')

          expect(security_findings.map { |finding| finding['scanner']['id'] }.uniq.first)
            .to eq(scanner_sast.to_global_id.to_s)
          expect(security_findings.map { |finding| finding['scanner']['reportType'] }.uniq.first).to eq('SAST')
        end
      end
    end
  end
end
